package com.ys.service.tools.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ys.entity.business.TbRepeatWord;
import com.ys.service.tools.ToolsCheckRepeatService;
import com.ys.util.excel.ReadExcel;
import com.ys.vo.R;

@Service("toolsCheckRepeatService")
public class ToolsCheckRepeatServiceImpl implements ToolsCheckRepeatService {

    private static final Logger logger = LoggerFactory.getLogger(ToolsCheckRepeatServiceImpl.class);

	@Override
	public List<List<String>> readExcel(MultipartFile file) throws Exception {

		return ReadExcel.getRowsByInputStream(file.getInputStream(), 0);
	}

	@Override
	public R checkRepeat(String country, List<List<String>> rows, String text) {
		if (country == null || country.length() == 0) {
			return R.error("请选择国家");
		}
		text = text.replace(" ", "|")
			.replace(",", "|")
			.replace("【", "|")
			.replace("】", "|")
			.replace("?", "|")
			.replace("&", "|")
			.replace("--", "|");
		Map<String, Integer> NAME_NUM_MAP = new HashMap<String, Integer>();
		List<TbRepeatWord> listTbRepeatWord = new TbRepeatWord().setCountry(country).queryList();
		for(TbRepeatWord entity : listTbRepeatWord) {
			String name = entity.getName();
			String nameNew = "|" + name + "|";
			if (text.contains(nameNew)) {
				int count = 0;
				int start = 0;
				while (true) {
					int index = text.indexOf(nameNew, start);
		            if (index != -1) {
		                //找到后次数增加
		                count++;
		                //找到对应字符所在索引，当找到后，将下次寻找的位置转换到当前已找到的位置
		                start = start + nameNew.length() - 1 + index;
		            } else {
		                break;
		            }
		        }
				NAME_NUM_MAP.put(name, count);
			}
//			for(List<String> listStr : rows) {
//				for(String str : listStr) {
//					if (str.contains(name)) {
//						Integer num = NAME_NUM_MAP.containsKey(name) ? NAME_NUM_MAP.get(name) : 1;
//						NAME_NUM_MAP.put(name, num);
//					}
//				}
//			}
		}
		
		List<CheckRepeatDto.RowDto> rows2 = new ArrayList<CheckRepeatDto.RowDto>();
		for(Entry<String, Integer> e : NAME_NUM_MAP.entrySet()) {
			rows2.add(new CheckRepeatDto.RowDto(e.getKey(), e.getValue()));
		}
		CheckRepeatDto dto = new CheckRepeatDto(rows2);
		return R.ok(dto);
	}
}
